//
//  FirstViewController.m
//  MyAppDemo
//
//  Created by 千锋 on 15/12/5.
//  Copyright (c) 2015年 Aike. All rights reserved.
//

#import "FirstViewController.h"

#import "NewsListModel.h"
#import "NewsDetailViewController.h"

#import "AFNetworking.h"


#import "GDataXMLNode.h"

@interface FirstViewController ()<UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>
{
    NSXMLParser * _xmlPareser;
    UITableView * _tableView;
    NSMutableArray * _newsArray;
    NSArray * _elementArray;
    UIRefreshControl * _refreshCtrl;
    NSInteger _currentPage;
    UIActivityIndicatorView * _footerIndicatorView;
    BOOL _isRequest;
    NSString * _currentElementName;
    NewsListModel * _newsListModel;
    
}

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _currentPage = 1;
    self.title =@"开源首页";
    //[self requestData];
    [self createTableView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createTableView{
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight  = 100;
    _refreshCtrl = [[UIRefreshControl alloc]init];
    [_tableView addSubview:_refreshCtrl];
    _refreshCtrl.tintColor = [UIColor grayColor];
    _refreshCtrl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
    [_refreshCtrl addTarget:self action:@selector(onPull:) forControlEvents:UIControlEventValueChanged];
    _footerIndicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _tableView.tableFooterView = _footerIndicatorView;
    _footerIndicatorView.hidden = YES;
}
- (void)onPull:(UIRefreshControl *) sender
{
    NSLog(@"下拉刷新喽");
    // 下拉刷新总是请求第1页的数据
    [self requestData:1];
}

//-(void)requestUserListWithPage:(NSInteger)page{
//    _isRequest = YES;
//    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
//    NSMutableDictionary * postParam = [[NSMutableDictionary alloc]init];
//    postParam[@"id"] = @"44393";
//    NSString * url = SNS_USER_LIST_API;
//    NSLog(@"%@",url);
//    [manager POST:url parameters:postParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        _isRequest = NO;
//        dispatch_async(dispatch_get_main_queue(), ^{
//            _footerIndicatorView.hidden = YES;
//            [_footerIndicatorView stopAnimating];
//            [_refreshCtrl endRefreshing];
//            [_tableView reloadData];
//        });
//        if (page == 1) {
//            [_newsArray removeAllObjects];
//        }
//
//        _xmlPareser = responseObject;
//        // 设置代理
//        _xmlPareser.delegate = self;
//        // 开始解析
//        [_xmlPareser parse];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@", error.localizedDescription);
//    }];
//    
//}

//请求数据

-(void)requestData:(NSInteger)page{
    //创建URL
    NSString * newsDetailURL = @"http://www.oschina.net/action/api/news_list";
    //创建请求
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:newsDetailURL]];
    //3.通过异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        _newsArray =  [NewsListModel parseXMLWithData:data andPage:1];
        _isRequest = NO;
        NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dataDict);
        dispatch_async(dispatch_get_main_queue(), ^{
            _footerIndicatorView.hidden = YES;
            [_footerIndicatorView stopAnimating];
            [_refreshCtrl endRefreshing];
            [_tableView reloadData];
        });
//        if (!connectionError) {
//            if (page==1) {
//                [_newsArray removeAllObjects];
//            }
//        }
    }];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _newsArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"CELL";
    // 复用
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    NewsListModel * model = _newsArray[indexPath.row];
    cell.textLabel.text = model.title;
    cell.detailTextLabel.text = model.pubDate;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsListModel * model = _newsArray[indexPath.row];
    NewsDetailViewController * detailView = [[NewsDetailViewController alloc]init];
    NSString * detaiURL = [NSString stringWithFormat:@"http://www.oschina.net/action/api/news_detail?id=%@",model.ID];
    
    detailView.newsDetail = detaiURL;
    [self.navigationController pushViewController:detailView animated:YES];
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView.contentSize.height < scrollView.frame.size.height) {
        return;
    }
    if (scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height +20) {
        if (_isRequest == NO) {
            _footerIndicatorView.hidden = YES;
            [_footerIndicatorView  startAnimating];
            _currentPage++;
            [self requestData:_currentPage];
        }
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
